﻿using System;
using System.ComponentModel.Composition;
using System.Diagnostics;

namespace FTI.Logging
{
    [Export("SystemEventLog", typeof(IEventLogging))]
    public class EventLogging
        : IEventLogging
    {
        #region constant variables
        public const string source = "FTI";
        #endregion
        EventLog _appLog = null;

        public string Name
        {
            get { return String.Format("{0} Event Log", source); }
        }

        public EventLogging()
            : base()
        {
            _appLog = new EventLog(Name)
            {
                Source = source
            };
        }

        public bool Write(string message, EventLogEntryType pEntryType, SystemCategory pCategory)
        {
            return Write(message, pEntryType, pCategory, new byte[] { });
        }

        public bool Write(string message, EventLogEntryType pEntryType, SystemCategory pCategory, byte[] pData)
        {
            if (SourceExists)
            {
                try
                {
                    _appLog.WriteEntry(message, pEntryType, 0, (short)pCategory, pData);
                }
                catch
                {   // write error to the trace listeners if any are present.
                    Trace.Write(message, Enum.GetName(typeof(SystemCategory), pCategory));

                    return false;
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool SourceExists
        {
            get
            {
                try
                {
                    return EventLog.SourceExists(source, ".");
                }
                catch
                {   // when not elevated and the source does not exist this will always through
                    return false;
                }
            }
        }
    }
}
